package vsvteam.outsource.leanappandroid.activity.valuestreammap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.ArrayWheelAdapter;
import vsvteam.outsource.leanappandroid.R;
import vsvteam.outsource.leanappandroid.actionbar.ChangeProjectActivity;
import vsvteam.outsource.leanappandroid.actionbar.ExportActivity;
import vsvteam.outsource.leanappandroid.actionbar.SettingActivity;
import vsvteam.outsource.leanappandroid.actionbar.VersionActivity;
import vsvteam.outsource.leanappandroid.activity.home.VSVTeamBaseActivity;
import vsvteam.outsource.leanappandroid.adapter.ListProcessAdapter;
import vsvteam.outsource.leanappandroid.adapter.ListStepAdapter;
import vsvteam.outsource.leanappandroid.database.LeanAppAndroidSharePreference;
import vsvteam.outsource.leanappandroid.database.TProcessDataBase;
import vsvteam.outsource.leanappandroid.database.TProcessDataBaseHandler;
import vsvteam.outsource.leanappandroid.database.TProjectDatabaseHandler;
import vsvteam.outsource.leanappandroid.database.TProjectDataBase;
import vsvteam.outsource.leanappandroid.define.Constant;
import vsvteam.outsource.leanappandroid.quickaction.ActionItem;
import vsvteam.outsource.leanappandroid.quickaction.QuickAction;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class CreateProjectActivity extends VSVTeamBaseActivity implements OnClickListener,
		OnItemClickListener, OnItemLongClickListener {

	// =========================Control Define ==========================
	private WheelView wheelProcess;
	private Button btnAddProcess;
	private Button btnDoneCreatedProject;

	private ImageView btnSetting;
	private ImageView btnExport;
	private ImageView btnVersion;
	private ImageView btnChangedProject;

	private EditText editTextProcessName;
	private EditText editTextProcessDescription;
	private EditText editTextProcessStartPoint;
	private EditText editTextProcessEndPoint;
	private EditText editTextProcessOutPutInventory;
	private EditText editTextProcessDefectPercent;
	private EditText editTextProcessDefectNotes;
	private EditText editTextProcessUpTime;
	private EditText editTextProcessCommunication;
	private EditText editTextProcessValueAddingTime;
	private EditText editTextProcessNonValueAddingTime;
	private EditText editTextProcessStepName;

	private ToggleButton toggleBtnProcessDetail;

	private TextView txtProjectName;

	private ListView listProcess;
	private ListView listStep;
	// =========================Class Define ============================
	private TProjectDatabaseHandler tProjectDataBaseHandler;
	private TProcessDataBaseHandler tProcessDataBaseHandler;
	private LeanAppAndroidSharePreference leanAppAndroidSharePreference;
	private QuickAction mQuickAction;
	private QuickAction mQuickAction2;
	// =========================Variable Define =========================
	private String[] process = { "Part Procument", "Quality Checking", "Assembly", "Document" };
	private int _processCurrentId;
	private String[] project = new String[5];
	private ArrayList<HashMap<String, String>> ArrListProcess;
	private ArrayList<HashMap<String, String>> ArrListStep;
	private static final int DIALOG_DELETE_PROCESS = 1;
	private static final int DIALOG_DELETE_STEP = 2;

	/*
	 * handler to control the dialog win game
	 */
	public final Handler handler = new Handler() {
		@SuppressWarnings("deprecation")
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case DIALOG_DELETE_PROCESS:
			// Level Up
			{
				showDialog(DIALOG_DELETE_PROCESS);
				break;
			}
			}
			super.handleMessage(msg);
		}
	};

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		if (view == btnAddProcess) {
			// add new process
			addNewProcess();

		} else if (view == btnDoneCreatedProject) {
			gotoActivityInGroup(this, DrawMapActivity.class);
		} else if (view == btnExport) {
			Intent intentExport = new Intent(CreateProjectActivity.this, ExportActivity.class);
			startActivity(intentExport);
		} else if (view == btnSetting) {
			Intent intentSetting = new Intent(CreateProjectActivity.this, SettingActivity.class);
			startActivity(intentSetting);
		} else if (view == btnVersion) {
			// Intent intentVersion = new Intent(CreateProjectActivity.this,
			// VersionActivity.class);
			// startActivity(intentVersion);
			gotoActivityInGroup(CreateProjectActivity.this, VersionActivity.class);
		} else if (view == btnChangedProject) {
			// Intent intentChangeProject = new
			// Intent(CreateProjectActivity.this,
			// ChangeProjectActivity.class);
			// startActivity(intentChangeProject);
			gotoActivityInGroup(CreateProjectActivity.this, ChangeProjectActivity.class);
		}
	}

	/**
	 * add new process
	 */
	private void addNewProcess() {
		// check if some field is empty
		if ("".equals(editTextProcessCommunication.getText().toString())
				|| "".equals(editTextProcessDefectNotes.getText().toString())
				|| "".equals(editTextProcessDefectPercent.getText().toString())
				|| "".equals(editTextProcessDescription.getText().toString())
				|| "".equals(editTextProcessEndPoint.getText().toString())
				|| "".equals(editTextProcessName.getText().toString())
				|| "".equals(editTextProcessNonValueAddingTime.getText().toString())
				|| "".equals(editTextProcessOutPutInventory.getText().toString())
				|| "".equals(editTextProcessStartPoint.getText().toString())
				|| "".equals(editTextProcessUpTime.getText().toString())
				|| "".equals(editTextProcessValueAddingTime.getText().toString())) {
			Toast.makeText(CreateProjectActivity.this, "Fill all fields to add new process",
					Toast.LENGTH_LONG).show();
		} else {
			
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.page_create_project);

		initDataBase();

		initialize();

		initQuickAction();

		initQuickActionDialog();

	}

	private void initQuickActionDialog() {
		// delete action
		ActionItem deleteAction = new ActionItem();
		deleteAction.setTitle("Delete");
		// edit action
		ActionItem editAction = new ActionItem();
		editAction.setTitle("Edit");

		mQuickAction2 = new QuickAction(this);

		mQuickAction2.addActionItem(deleteAction);
		mQuickAction2.addActionItem(editAction);

		// setup the action item click listener
		mQuickAction2.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
			@Override
			public void onItemClick(int pos) {
				Log.e("pos", "pos " + pos);
				if (pos == 0) { // delete item selected
					Toast.makeText(CreateProjectActivity.this, "delete", Toast.LENGTH_LONG).show();
					// show dialog delete process
					// sendMS(DIALOG_DELETE_PROCESS);
				} else if (pos == 1) {// edit item seleted
					Intent i = new Intent(CreateProjectActivity.this, EditProcessActivity.class);
					startActivity(i);
				}
			}
		});

	}

	/**
	 * initialize Quick Action
	 */
	private void initQuickAction() {
		// delete action
		ActionItem deleteAction = new ActionItem();
		deleteAction.setTitle("Delete");
		// edit action
		ActionItem editAction = new ActionItem();
		editAction.setTitle("Edit");

		mQuickAction = new QuickAction(this);

		mQuickAction.addActionItem(deleteAction);
		mQuickAction.addActionItem(editAction);

		// setup the action item click listener
		mQuickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
			@Override
			public void onItemClick(int pos) {
				Log.e("pos", "pos " + pos);
				if (pos == 0) { // delete item selected
					Toast.makeText(CreateProjectActivity.this, "delete", Toast.LENGTH_LONG).show();
					// show dialog delete process
					// mQuickAction2.show(listStep, false);
					// sendMS(DIALOG_DELETE_PROCESS);
				} else if (pos == 1) {// edit item seleted
					Intent i = new Intent(CreateProjectActivity.this, EditProcessActivity.class);
					startActivity(i);
				}
			}
		});

	}

	@SuppressWarnings("deprecation")
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog;
		switch (id) {
		case DIALOG_DELETE_PROCESS: {
			DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						// Share button clicked
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						// Exit button clicked
						finish();
						break;
					}
				}
			};
			AlertDialog.Builder builder = new AlertDialog.Builder(CreateProjectActivity.this);
			builder.setMessage(R.string.text_delete_process).setIcon(R.drawable.ic_launcher)
					.setTitle(getString(R.string.app_name)).setCancelable(false)
					.setPositiveButton(R.string.text_delete_positive, dialogClickListener)
					.setNegativeButton(R.string.text_delete_negative, dialogClickListener);
			return builder.create();
		}
		case DIALOG_DELETE_STEP: {
			DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						// Share button clicked
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						// Exit button clicked
						finish();
						break;
					}
				}
			};
			AlertDialog.Builder builder = new AlertDialog.Builder(CreateProjectActivity.this);
			builder.setMessage(R.string.text_delete_step).setIcon(R.drawable.ic_launcher)
					.setTitle(getString(R.string.app_name)).setCancelable(false)
					.setPositiveButton(R.string.text_delete_positive, dialogClickListener)
					.setNegativeButton(R.string.text_delete_negative, dialogClickListener);
			return builder.create();
		}

		default:
			dialog = super.onCreateDialog(id);
			break;
		}
		return dialog;
	}

	private void sendMS(final int wh) {
		new CountDownTimer(1000, 100) {

			@Override
			public void onTick(long millisUntilFinished) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onFinish() {
				Message ms = new Message();
				ms.what = wh;
				handler.sendMessage(ms);
			}
		}.start();
	}

	/**
	 * initialize variable
	 */
	private void initialize() {
		wheelProcess = (WheelView) findViewById(R.id.wheel_process);
		wheelProcess.setVisibleItems(5);
		wheelProcess.setCurrentItem(0);
		wheelProcess.setViewAdapter(new ProcessArrayAdapter(this, process, 0));

		// Button
		btnAddProcess = (Button) findViewById(R.id.btn_add_process);
		btnAddProcess.setOnClickListener(this);
		btnSetting = (ImageView) findViewById(R.id.img_create_project_setting);
		btnSetting.setOnClickListener(this);
		btnDoneCreatedProject = (Button) findViewById(R.id.btn_process_i_am_done);
		btnDoneCreatedProject.setOnClickListener(this);
		btnExport = (ImageView) findViewById(R.id.img_create_project_export);
		btnExport.setOnClickListener(this);
		btnSetting = (ImageView) findViewById(R.id.img_create_project_setting);
		btnSetting.setOnClickListener(this);
		btnVersion = (ImageView) findViewById(R.id.img_create_project_version);
		btnVersion.setOnClickListener(this);
		btnChangedProject = (ImageView) findViewById(R.id.img_create_project_change_project);
		btnChangedProject.setOnClickListener(this);

		// EditText
		editTextProcessStepName = (EditText) findViewById(R.id.editText_process_step_name);
		editTextProcessCommunication = (EditText) findViewById(R.id.editText_communication);
		editTextProcessDefectNotes = (EditText) findViewById(R.id.editText_defect_notes);
		editTextProcessDefectPercent = (EditText) findViewById(R.id.editText_defect_percent);
		editTextProcessDescription = (EditText) findViewById(R.id.editText_process_description);
		editTextProcessEndPoint = (EditText) findViewById(R.id.editText_process_customer);
		editTextProcessName = (EditText) findViewById(R.id.editText_process_name);
		editTextProcessNonValueAddingTime = (EditText) findViewById(R.id.editText_non_value_adding_time);
		editTextProcessOutPutInventory = (EditText) findViewById(R.id.editText_output_inventory);
		editTextProcessStartPoint = (EditText) findViewById(R.id.editText_process_supplier);
		editTextProcessUpTime = (EditText) findViewById(R.id.editText_uptime);
		editTextProcessValueAddingTime = (EditText) findViewById(R.id.editText_value_adding_time);

		// Toggle Button
		toggleBtnProcessDetail = (ToggleButton) findViewById(R.id.switch_process);

		// TextView project name
		txtProjectName = (TextView) findViewById(R.id.txt_projectName);
		txtProjectName.setText("Project " + leanAppAndroidSharePreference.getProjectNameActive()
				+ " is created.");

		// ArrListProcess process
		listProcess = (ListView) findViewById(R.id.list_process);
		// set header for ArrListProcess view
		LayoutInflater inflater = this.getLayoutInflater();
		View header = inflater.inflate(R.layout.listprocess_header, null);
		listProcess.addHeaderView(header);
		// calculate for list process
		populateListProcess();
		ListProcessAdapter listProcessAdapter = new ListProcessAdapter(this, ArrListProcess);
		listProcess.setAdapter(listProcessAdapter);
		listProcess.setOnItemClickListener(this);
		listProcess.setOnItemLongClickListener(this);
		listProcess.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

		// ArrListProcess step
		listStep = (ListView) findViewById(R.id.list_step);
		LayoutInflater inflaterStep = this.getLayoutInflater();
		View headerStep = inflaterStep.inflate(R.layout.liststep_header, null);
		listStep.addHeaderView(headerStep);
		// calculate for listvie
		populateListStep();
		ListStepAdapter listStepAdapter = new ListStepAdapter(this, ArrListStep);
		listStep.setAdapter(listStepAdapter);
		listStep.setOnItemClickListener(this);
		listStep.setOnItemLongClickListener(this);
		listStep.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
	}

	private void initDataBase() {
		// init share preference
		leanAppAndroidSharePreference = LeanAppAndroidSharePreference.getInstance(this);

		// init database
		tProcessDataBaseHandler = new TProcessDataBaseHandler(this);

		// Reading all process
//		Log.d("Reading: ", "Reading all contacts..");
//		List<TProcessDataBase> listProcess = tProcessDataBaseHandler.getAllProcess();

//		if (listProcess.size() > 0) {
//			process = new String[listProcess.size()];
//			for (int i = 0; i < listProcess.size(); i++) {
//				process[i] = listProcess.get(i).getProcessName().toString();
//			}
//		} else
//			process = new String[] { "No Proces", "No Process", "No process", "No Process",
//					"No Project" };
	}

	/**
	 * Adapter for string based wheel. Highlights the current value.
	 */
	private class ProcessArrayAdapter extends ArrayWheelAdapter<String> {
		// Index of current item
		int currentItem;
		// Index of item to be highlighted
		int currentValue;

		/**
		 * Constructor
		 */
		public ProcessArrayAdapter(Context context, String[] items, int current) {
			super(context, items);
			this.currentValue = current;
			setTextSize(24);
		}

		@Override
		protected void configureTextView(TextView view) {
			super.configureTextView(view);
			if (currentItem == currentValue) {
				view.setTextColor(0xFF0000F0);
			}
			view.setTypeface(Typeface.SANS_SERIF);
		}

		@Override
		public View getItem(int index, View cachedView, ViewGroup parent) {
			currentItem = index;
			return super.getItem(index, cachedView, parent);
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (arg0 == listProcess && arg2 > 0) {
			mQuickAction.show(arg1, true);
			listProcess.requestFocus(arg2);
			mQuickAction.setAnimStyle(QuickAction.ANIM_GROW_FROM_CENTER);
		} else if (arg0 == listStep && arg2 > 0) {
			mQuickAction.show(arg1, false);
			listStep.requestFocus(arg2);
			mQuickAction.setAnimStyle(QuickAction.ANIM_GROW_FROM_CENTER);
		}
		return true;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (arg0 == listProcess && arg2 > 0) {
			mQuickAction.show(arg1, true);
			mQuickAction.setAnimStyle(QuickAction.ANIM_GROW_FROM_CENTER);
		} else if (arg0 == listStep && arg2 > 0) {
			mQuickAction.show(arg1, false);
			mQuickAction.setAnimStyle(QuickAction.ANIM_GROW_FROM_CENTER);
		}
	}

	/**
	 * calculate list step value
	 */
	private void populateListStep() {
		ArrListStep = new ArrayList<HashMap<String, String>>();

		HashMap<String, String> temp = new HashMap<String, String>();
		temp.put(Constant.FIRST_COLUMN, "Colored Notebooks");
		temp.put(Constant.SECOND_COLUMN, "By NavNeet");
		ArrListStep.add(temp);

		HashMap<String, String> temp1 = new HashMap<String, String>();
		temp1.put(Constant.FIRST_COLUMN, "Diaries");
		temp1.put(Constant.SECOND_COLUMN, "By Amee Products");
		ArrListStep.add(temp1);

		HashMap<String, String> temp2 = new HashMap<String, String>();
		temp2.put(Constant.FIRST_COLUMN, "Note Books and Stationery");
		temp2.put(Constant.SECOND_COLUMN, "By National Products");
		ArrListStep.add(temp2);

		HashMap<String, String> temp3 = new HashMap<String, String>();
		temp3.put(Constant.FIRST_COLUMN, "Corporate Diaries");
		temp3.put(Constant.SECOND_COLUMN, "By Devarsh Prakashan");
		ArrListStep.add(temp3);

		HashMap<String, String> temp4 = new HashMap<String, String>();
		temp4.put(Constant.FIRST_COLUMN, "Writing Pad");
		temp4.put(Constant.SECOND_COLUMN, "By TechnoTalaktive Pvt. Ltd.");
		ArrListStep.add(temp4);
	}

	/**
	 * calculate list process value
	 */
	private void populateListProcess() {
		ArrListProcess = new ArrayList<HashMap<String, String>>();
		if (process.length > 0)
			for (int i = 0; i < process.length; i++) {
				HashMap<String, String> temp = new HashMap<String, String>();
				temp.put(Constant.FIRST_COLUMN, "Colored Notebooks");
				temp.put(Constant.SECOND_COLUMN, process[i]);
				temp.put(Constant.THIRD_COLUMN, "Rs. 200");
				ArrListProcess.add(temp);
			}
		else {
			HashMap<String, String> temp = new HashMap<String, String>();
			temp.put(Constant.FIRST_COLUMN, "Colored Notebooks");
			temp.put(Constant.SECOND_COLUMN, "By NavNeet");
			temp.put(Constant.THIRD_COLUMN, "Rs. 200");
			ArrListProcess.add(temp);

			HashMap<String, String> temp1 = new HashMap<String, String>();
			temp1.put(Constant.FIRST_COLUMN, "Diaries");
			temp1.put(Constant.SECOND_COLUMN, "By Amee Products");
			temp1.put(Constant.THIRD_COLUMN, "Rs. 400");
			ArrListProcess.add(temp1);

			HashMap<String, String> temp2 = new HashMap<String, String>();
			temp2.put(Constant.FIRST_COLUMN, "Note Books and Stationery");
			temp2.put(Constant.SECOND_COLUMN, "By National Products");
			temp2.put(Constant.THIRD_COLUMN, "Rs. 600");
			ArrListProcess.add(temp2);

			HashMap<String, String> temp3 = new HashMap<String, String>();
			temp3.put(Constant.FIRST_COLUMN, "Corporate Diaries");
			temp3.put(Constant.SECOND_COLUMN, "By Devarsh Prakashan");
			temp3.put(Constant.THIRD_COLUMN, "Rs. 800");
			ArrListProcess.add(temp3);

			HashMap<String, String> temp4 = new HashMap<String, String>();
			temp4.put(Constant.FIRST_COLUMN, "Writing Pad");
			temp4.put(Constant.SECOND_COLUMN, "By TechnoTalaktive Pvt. Ltd.");
			temp4.put(Constant.THIRD_COLUMN, "Rs. 100");
			ArrListProcess.add(temp4);
		}
	}

	protected void onPause() {
		super.onPause();
		mQuickAction.dismiss();
		Log.e("onPause", "onPause");
	}

	@Override
	public void onResume() {
		super.onResume();
		Log.e("onResume", "onResume");
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.e("onDestroy", "onDestroy");
	}
}
